package cn.xutongxue.book_sales.controller;

import cn.xutongxue.book_sales.base.Result;
import cn.xutongxue.book_sales.entity.Carts;
import cn.xutongxue.book_sales.entity.Goods;
import cn.xutongxue.book_sales.service.CartsService;
import cn.xutongxue.book_sales.service.GoodsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * Created By TongXue Xu on 2021/12/22 21:49
 */
@RestController
@RequestMapping("/cart")
public class CartsController {

    @Resource
    private CartsService cartsService;

    @Resource
    private GoodsService goodsService;

    @GetMapping("/get")
    public Result get(@RequestParam("user_id") Integer userId) {

        QueryWrapper<Carts> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<Carts> list = cartsService.list(wrapper);
        return Result.ok("获取成功" ,list);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Carts cart) {

        BigDecimal newPrice = new BigDecimal(cart.getCartNum() * cart.getBooksPrice().doubleValue());
        cart.setSumPrice(newPrice);
        if (cartsService.save(cart)) {
            return Result.ok("添加成功",null);
        }
        return Result.fail(1201,"未知错误");
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Carts carts) {

        if(cartsService.removeById(carts.getCartId())) {
            return Result.ok("删除成功",null);
        }
        return Result.fail(1203,"删除失败");
    }


    @PostMapping("/update")
    public Result update(@RequestBody Carts carts) {

        QueryWrapper<Carts> wrapper = new QueryWrapper<>();
        wrapper.eq("cart_id", carts.getCartId());

        Carts temp = cartsService.getById(carts.getCartId());
        temp.setCartNum(carts.getCartNum());
        BigDecimal newPrice = new BigDecimal(((carts.getCartNum() * temp.getBooksPrice().doubleValue())));
        temp.setSumPrice(newPrice);
        cartsService.update(temp,wrapper);
        return Result.ok("修改成功");
    }
}
